<?php
namespace app\index\controller;

use think\Controller;
use think\Db;
/**
 * 注册控制器
*/
class Register extends Controller
{
	/**
	 * 注册首页
	 *
	 * **/
	public function index()
    {
    	return view('index');
    }
    
    /**
	 * 注册
     * Method Post
     * @param  string post.email :注册邮箱
     * @param  string post.password :注册密码
	 *
     * @return json  success:邮件发送成功 error:注册失败
     * */
    public function register()
	{
		try{
			//验证是否为post提交
			if(Request()->isPost()){
				$input['email'] = input('post.email');
				$input['password'] = encrypt(input('post.password'));
				$input['status'] = 3;
				$tokens = $this->token();
				$input['token'] = $tokens;
				//开始事务
				Db::startTrans();
				$res = Db::table('business')->insertGetId($input);
				if(!$res){
					//注册失败
					throw new \PDOException("注册失败");
				}
				//成功提交
				Db::commit();
				$title = "商家注册";
				$content = "亲爱的" . $input['email'] . "：<br/>感谢您在我站注册了新帐号。<br/>请点击链接激活您的帐号。<br/><a href='http://192.168.1.101/company/shoping/shop/public/index/Register/doRegister?token=" .$tokens. "' target='_blank'>http://192.168.1.101/company/shoping/shop/public/index/Register/doRegister?token=" .$tokens."</a><br/>如果以上链接无法点击，请将它复制到你的浏览器地址栏中进入访问，该链接24小时内有效。<br/>如果此次激活请求非你本人所发，请忽略本邮件。<br/>";
				$result = sendMail($input['email'],$title,$content);
				if($result){
					//发送成功
					$success = ['success'=>"邮件发送成功，请注意查看邮箱"];
					return json($success);
				}
			}
		}catch (\PDOException $e){
			//失败回滚
			Db::rollback();
			$error = ['error'=>$e->getMessage()];
			return json($error);
		}
		
	}
	
	/**
	 *
	 *	判断邮箱是否存在
	 *	Method Post
	 * 	@param string post.email 要验证的邮箱
	 *
	 * 	@return boolean true 存在  false  不存在
	 */
	public function mailbox()
	{
		//验证是否为post提交
		if(Request()->isPost()){
			$email = input('post.email');
			$result = Db::table('business')->where('email',$email)->find();
			if($result){
				return true;
			}else{
				return false;
			}
		}
	}
	/**
	 * 注册验证
	 * Method Get
	 * @param string $_GET['token']
	 * **/
	public function doRegister()
	{
		if(trim($_GET['token'])){
			$result = Db::table('business')->where('token',$_GET['token'])->find();
			if($result){
				$res = Db::table('business')->where('token',$result['token'])->update(['status'=>2]);
				if($res){
					return view('success');
				}else{
					return view('fail');
				}
			}
		}
	}
	
	/**
	 * 生成token
	 * @return string $token
	 * */
	public function token($length = 10)
	{
		// 密码字符集，可任意添加你需要的字符
		$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
		$token = time();
		for ( $i = 0; $i < $length; $i++ )
		{
			$token .= $chars[ mt_rand(0, strlen($chars) - 1) ];
		}
		return $token;
	}
	
}
